package me.shiqiang.im.consumer;

import com.aliyun.openservices.ons.api.*;
import me.shiqiang.im.enums.MessageCmd;
import me.shiqiang.im.msg.SyncFriendReq;
import me.shiqiang.im.msg.SyncFriendResp;
import me.shiqiang.im.service.ChatSwitchService;
import me.shiqiang.im.service.UserClient;
import me.shiqiang.im.utils.JsonUtils;
import me.shiqiang.im.vo.Friend;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author cuishiqiang
 * @date 2017/12/16 下午7:57
 */
@Component("FriendMsgConsumer")
public class FriendMsgConsumer implements MessageListener {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    UserClient userClient;

    @Autowired
    ChatSwitchService chatSwitchService;

    @Value("${send.topic}")
    String topic;

    @Autowired
    Producer producer;

    @Override
    public Action consume(Message message, ConsumeContext context) {
        String msgStr = new String(message.getBody());
        logger.info("收取消息：{}", msgStr);
        try {
            SyncFriendReq msg = JsonUtils.getInstance().fromJson(msgStr, SyncFriendReq.class);
            if (!chatSwitchService.chatSwitch(msg.getUserId())) {
                return Action.CommitMessage;
            }
            Collection<Friend> friends = userClient.getFriends(msg.getUserId());
            SyncFriendResp resp = new SyncFriendResp();
            resp.setFriends(friends);

            String s = JsonUtils.getInstance().toJson(resp);
            logger.info(s);
            Message rtnMsg = new Message(topic, msg.getUserId().toString(), MessageCmd.SYNC_FRIEND_RESP, s.getBytes());
            producer.send(rtnMsg);
            return Action.CommitMessage;
        } catch (Exception e) {
            logger.error(String.format("处理消息失败,msg:%s", msgStr), e);
            return Action.ReconsumeLater;
        }
    }
}
